using System;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mail;
using System.Web.UI;
using System.Xml;
using log4net;

/*	-----------------------------------------------------------------------	
	Copyright:	umlungu consulting (pty) ltd
	Author:		Alan Benington
	Started:	2008-06-14
	Status:		release	
	Version:	2.0.0
	Build:		20080614
	License:	GNU General Public License
	-----------------------------------------------------------------------	*/

/*	-----------------------------------------------------------------------	
	Development Notes:
	==================
	20080614:	Initial release.
	---------------------------------------------------------------------------	*/

namespace umlungu.engineX.blogX.WebsiteX {
	/// <summary>
	/// Description of the WebsiteXNewsletter class.
	/// <para>Additional information about the class</para>
	/// </summary>
	public class WebsiteXNewsletter : x_broker {
		#region Invisible properties
		#endregion

		#region Constant name strings
        private const string logid = "WebsiteXNewsletter";
		#endregion

		#region Constant error strings
		private const string error_no_error = "Not an error";
		private const string error_newsletter = "WebsiteX Newsletter error::";
		private const string error_newsletter_test = " test error";
		private const string error_newsletter_email = " Error updating email notification: ";
		#endregion

		#region Visible properties
		public static readonly ILog Logger = LogManager.GetLogger(typeof(WebsiteXNewsletter));

		#endregion

		#region Constructors/Destructors
		/// <overloads>Constructor</overloads>
		/// <summary>Default constructor</summary>
		/// <param name="thispage">The web application Page object</param>
		public WebsiteXNewsletter(displayX thispage) : base(thispage) {
			log4net.Config.XmlConfigurator.Configure();
		}
		#endregion

		#region Public methods
		public override void Process(string type) {
			Logger.Info(String.Concat("_Process:", type));
			switch (type) {
				case "subscribe": subscribe(); break;
				case "unSubscribe": unSubscribe(); break;
				case "validateEmail": validateEmailAddress(); break;
			}
		}
		#endregion

		#region Protected methods
		#endregion

		#region Private methods
		private void subscribe() {
			try {
				//get email address from UI
				string emailAddress = UIPage.UserProfile.Value("Email");

				//Login using administrator account and get token
				recruitX recX = new recruitX();
				XmlDocument result = recX.Token("administrator", "customer");
                string tokenValue = result.SelectSingleNode("blogX/Result/token").InnerText.ToString();

                //add user, if result code != 0 then an error has occurred
                result = recX.Add(tokenValue,"websitex", "", "", emailAddress );

                Logger.Debug(result.InnerXml.ToString());

                if (result.SelectSingleNode("blogX/Result/Result_Code").InnerText.ToString()  == "0") {
					Logger.Info(String.Concat("Added email address to recruit list: ", emailAddress));
				} else {
					Logger.Info(String.Concat("Error adding email address to the recruit list: ", emailAddress));
                    throw (new displayException("newsletter_subscriber_exists"));
				}
        
			} catch (displayException e) {
				throw (e);
			} catch (x_exception e) {
				throw (new x_exception("error_unknown", String.Concat(error_newsletter, error_newsletter_email, e.Code, " - ", e.Message)));
			} catch (Exception e) {
				throw (new x_exception("error_unknown", String.Concat(error_newsletter, error_newsletter_email, e.Message)));
			}
		}

		private void unSubscribe() {
			try {
                //get email address from UI
                string emailAddress = UIPage.UserProfile.Value("Email");

                //Login using administrator account and get token
                recruitX recX = new recruitX();
                XmlDocument result = recX.Token("administrator", "customer");
                string tokenValue = result.SelectSingleNode("blogX/Result/token").InnerText.ToString();

                //delete user here
                result = recX.RemoveUser(tokenValue, emailAddress); 

				//check to see if email address was unsubscribed
                if (result.SelectSingleNode("blogX/Result/Result_Code").InnerText.ToString() == "0") {
                    Logger.Info(String.Concat("Deleted email address from user list: ", emailAddress));
				} else {
                    //redirect to error page 
                    throw (new displayException("newsletter_subscriber_notexist"));
				}
			} catch (displayException e) {
				throw (e);
			} catch (x_exception e) {
				throw (new x_exception("error_unknown", String.Concat(error_newsletter, error_newsletter_email, e.Code, " - ", e.Message)));
			} catch (Exception e) {
				throw (new x_exception("error_unknown", String.Concat(error_newsletter, error_newsletter_email, e.Message)));
			}

		}

		private void validateEmailAddress() {
			try {
				//get email address and secret field from url
				string emailAddressURL = _GetRequest(false, "name", "");
				string secretFieldURL = _GetRequest(false, "id", "");

                //Login using administrator account and get token
                recruitX recX = new recruitX();
                XmlDocument result = recX.Token("administrator", "customer");
                string tokenValue = result.SelectSingleNode("blogX/Result/token").InnerText.ToString();

                result = recX.RegisterRecruit(tokenValue, secretFieldURL, "", "", "", "", "");
				
                //check to see if email address was validated
                if (result.SelectSingleNode("blogX/Result/Result_Code").InnerText.ToString() == "0") {
				    Logger.Info(String.Concat("Email account updated from recruit to user: ", emailAddressURL));
				} else {
					//redirect to the "Email address supplied does not exist in list" page
					throw (new displayException("newsletter_subscriber_notexist"));
				}
			} catch (displayException e) {
				throw (e);
			} catch (x_exception e) {
				throw (new x_exception("error_unknown", String.Concat(error_newsletter, error_newsletter_email, e.Code, " - ", e.Message)));
			} catch (Exception e) {
				throw (new x_exception("error_unknown", String.Concat(error_newsletter, error_newsletter_email, e.Message)));
			}
		}
		#endregion
	}
}
